"""
在线词典 ： 服务端逻辑处理
"""

from dict_db import *
from multiprocessing import Process
from socket import *


class Dict_Sevrver:
    def __init__(self, host="", port=0):
        self.host = host
        self.port = port
        self.ADDR = (host, port)
        self.sock = self.all()

    def all(self):
        sock = socket()
        sock.bind(self.ADDR)
        return sock

    def main(self):
        self.sock.listen(5)
        print("端口：", self.port)
        while True:
            try:
                conn, addr = self.sock.accept()
                print("已连接：", addr)
            except:
                self.sock.close()
                break
            d = Dict_s(conn, addr)
            d.start()


class Dict_s(Process):
    def __init__(self, conn, addr):
        self.conn = conn
        self.addr = addr
        super().__init__()
        self.dict = Dict()

    def run(self) -> None:
        while True:
            data = self.conn.recv(1024)
            print(data)
            tmp = data.decode().split("\t")
            if not data or data == "E":
                break
            elif tmp[0] == "R":
                self.enrol(self.conn, tmp[1], tmp[2])
            elif tmp[0] == "L":
                self.enter(self.conn, tmp[1], tmp[2])
        self.dict.close()
        self.conn.close()

    def enrol(self, conn, user, password):  # 注册
        a = self.dict.insert_user(user, password)
        if a == True:
            conn.send(b"T")
        else:
            conn.send(b"F")

    def enter(self, conn, user, password):
        a = self.dict.enter_user(user, password)
        if a == True:
            conn.send(b"T")
        else:
            conn.send(b"F")


if __name__ == '__main__':
    s = Dict_Sevrver("0.0.0.0", 7779)
    s.main()
